<template>
  <div class="app-container">
    <el-card>
      <el-page-header @back="goBack">
        <template #content>
          <div
            class="flex items-center"
            style="display: flex; justify-content: space-between"
          >
            <div style="display: flex; align-items: center">
              <div>
                {{
                  route.query.readonly
                    ? "查看纸张盘点单信息"
                    : route.query.id
                    ? "编辑纸张盘点单信息"
                    : "新增纸张盘点单"
                }}
              </div>
              <el-tag
                v-if="route.query.code"
                :type="tagType"
                style="margin-left: 10px"
              >
                {{ route.query.code }}
              </el-tag>
            </div>
          </div>
        </template>
        <template #extra>
          <div>
            <el-button
              v-if="!readonly"
              class="button"
              type="primary"
              :loading="btnLoading"
              @click="handleSubmit"
            >
              保 存
            </el-button>
          </div>
        </template>
      </el-page-header>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-collapse v-model="activeNames">
        <el-collapse-item disabled title="基本信息" name="1">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">基本信息</span>
          </template>
          <div>
            <el-form
              :model="form"
              :rules="rules"
              :disabled="readonly"
              ref="cancellationRef"
              label-width="130px"
            >
              <el-row :gutter="20">
                <!-- <el-col :span="8">
                   <el-form-item label="盘点日期" prop="inventoryDate">
                    <el-date-picker
                      v-model="form.inventoryDate"
                      style="width: 100%"
                      type="datetime"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                    />
                  </el-form-item> 
                </el-col> -->

                <el-col :span="8">
                  <el-form-item label="盘点月份" prop="inventoryMonth">
                    <el-date-picker
                      v-model="form.inventoryMonth"
                      format="YYYY-MM"
                      value-format="YYYY-MM"
                      style="width: 100%"
                      type="month"
                      placeholder="选择盘点月份"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="盘点仓库" prop="inventoryStore">
                    <el-select
                      v-model="form.inventoryStore"
                      placeholder="请选择"
                      style="width: 100%"
                      @change="handleType"
                    >
                      <el-option
                        v-for="item in inventory_store"
                        :key="item.label"
                        :label="item.label"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="盘点人">
                    <el-input
                      v-model="form.inventoryUser"
                      maxlength="30"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8" v-if="readonly">
                  <el-form-item label="确认人">
                    <el-input
                      v-model="form.confirmUser"
                      maxlength="30"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8" v-if="readonly">
                  <el-form-item label="确认时间">
                    <el-date-picker
                      v-model="form.confirmDate"
                      style="width: 100%"
                      type="date"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="备注">
                    <el-input
                      v-model="form.remark"
                      type="textarea"
                      placeholder="请输入内容"
                      style="width: 100%"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
      </el-collapse>
      <el-collapse v-model="activeNames">
        <el-collapse-item disabled title="基本信息" name="1">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">盘点明细</span>
          </template>
          <div>
            <el-table
              :data="mesInventoryDetailList"
              v-loading="loading"
              border
              style="width: 100%"
              :header-cell-class-name="must"
            >
              <el-table-column
                type="index"
                label="序号"
                width="60"
                align="center"
              />
              <el-table-column
                prop="material"
                label="纸张类型"
                width="80"
                align="center"
              >
                <template #default="scope">
                  <dict-tag
                    :options="mes_paper_material"
                    :value="scope.row.material"
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="code"
                label="纸张编码"
                min-width="100"
                align="center"
              ></el-table-column>
              <!-- <el-table-column prop="originalCode" label="自有编码" align="center">
                            </el-table-column> -->
              <el-table-column
                prop="name"
                min-width="120"
                label="纸张名称"
                align="center"
              ></el-table-column>
              <el-table-column prop="specs" label="规格" align="center">
                <template #default="scope">
                  <dict-tag
                    :options="mes_paper_specs"
                    :value="scope.row.specs"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="brand" label="品牌" align="center">
                <template #default="scope">
                  <dict-tag
                    :options="mes_paper_brand"
                    :value="scope.row.brand"
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="weight"
                label="定量"
                align="center"
              ></el-table-column>
              <el-table-column prop="unit" label="单位" align="center">
                <template #default="scope">
                  <dict-tag :options="mes_paper_unit" :value="scope.row.unit" />
                </template>
              </el-table-column>
              <!-- <el-table-column
                v-if="form.inventoryStore == 0"
                prop="monthEnter"
                label="本月入库"
                align="center"
              ></el-table-column>
              <el-table-column
                v-if="form.inventoryStore == 0"
                prop="monthLeave"
                label="本月出库"
                align="center"
              ></el-table-column> -->
              <el-table-column
                v-if="form.inventoryStore == 0"
                prop="quantity"
                label="库存数量"
                width="120"
                align="center"
              ></el-table-column>
              <!-- <el-table-column
                v-if="form.inventoryStore != 0"
                prop="dayEnter"
                label="入库"
                align="center"
              ></el-table-column>
              <el-table-column
                v-if="form.inventoryStore != 0"
                prop="dayLeave"
                label="出库"
                align="center"
              ></el-table-column> -->
              <!-- <el-table-column
                v-if="form.inventoryStore != 0"
                prop="reportNumber"
                label="报工用纸数量"
                align="center"
              ></el-table-column> -->
              <el-table-column
                v-if="form.inventoryStore != 0"
                prop="quantity"
                label="库存数量"
                width="120"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="inventoryNumber"
                label="盘点数量"
                width="120"
                align="center"
              >
                <template #default="{ row }">
                  <el-input
                    @change="changeInventoryNumber(row)"
                    v-model="row.inventoryNumber"
                    :disabled="readonly"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop="profitLoss"
                label="盘盈/盘亏"
                width="120"
                align="center"
              >
                <!-- 字典 -->
                <!-- <template #default="{ row }">
                  <el-select
                    v-model="row.profitLoss"
                    :disabled="readonly"
                    placeholder="请选择"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in ems_inventorysheet_surplusloss"
                      :key="item.label"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </template> -->
              </el-table-column>
              <el-table-column
                prop="reason"
                label="差额原因"
                width="120"
                align="center"
              >
                <template #default="{ row }">
                  <el-input
                    v-model="row.reason"
                    :disabled="readonly"
                  ></el-input>
                </template>
              </el-table-column>
              <!-- <el-table-column fixed="right" label="操作" align="center">
                                <template #default="scope">
                                    <el-button link type="primary" :disabled="readonly" size="small"
                                        @click="handleDel(scope.row)">删除</el-button>
                                </template>
                            </el-table-column> -->
            </el-table>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-card>
    <!-- <SearchWorkBench
      :visible="searchVisible"
      @changeUpdate="changeSearchWorkBenchData"
      @cancel="
        () => {
          searchVisible = false;
        }
      "
    ></SearchWorkBench> -->
  </div>
</template>
<script setup>
import { computed } from "vue";
import { toNumber } from "@/utils/ruoyi";
// import SearchWorkBench from "@/components/SearchWorkBench";
import useTagsViewStore from "@/store/modules/tagsView";
const tagsViewStore = useTagsViewStore();
import { getList as getDataList } from "@/api/basicInfo/workbench";

import {
  addInventory,
  updateInventory,
  getIdInventory,
  detailsInventory,
} from "@/api/storage/inventorySheet.js";
const { proxy } = getCurrentInstance();
const {
  mes_paper_material,
  ems_inventorysheet_surplusloss,
  mes_paper_unit,
  mes_paper_brand,
  mes_paper_specs,
} = proxy.useDict(
  "mes_paper_brand",
  "mes_paper_specs",
  "mes_paper_unit",
  "mes_paper_material",
  "ems_inventorysheet_surplusloss"
);
import { ElMessage, ElMessageBox, useDelayedRender } from "element-plus";
import useUserStore from "@/store/modules/user";
const router = useRouter();
const route = useRoute();
const activeNames = ["1"];
const cancellationRef = ref(null);
const mesInventoryDetailList = ref([]);
const readonly = ref(false);
const loading = ref(false);
const searchVisible = ref(false);
const btnLoading = ref(false);
const inventory_store = ref([]);
const data = reactive({
  form: {},
  rules: {
    inventoryStore: [
      { required: true, message: "请选择盘点仓库", trigger: "change" },
    ],
    inventoryMonth: [
      { required: true, message: "请选择盘点月份", trigger: "change" },
    ],
  },
});
const { form, rules } = toRefs(data);
const userInfo = useUserStore();
const tagType = computed(() => {
  return route.query.status == 1 ? "" : "danger";
});
readonly.value = route.query.readonly;
if (route.query.id) {
  getIdInventory(route.query.id).then((response) => {
    form.value = response.data;
    response.data.mesInventoryDetailList.forEach((item) => {
      mesInventoryDetailList.value.push({
        ...item.mesPaper,
        // monthEnter: item.monthEnter,
        // monthLeave: item.monthLeave,
        paperid: item.paperid,
        quantity: item.machineNumber,
        machineNumber: item.machineNumber,
        inventoryNumber: item.inventoryNumber,
        profitLoss: item.profitLoss ? item.profitLoss + "" : undefined,
        reason: item.reason,
        storeNumber: item.storeNumber,
      });
    });
  });
} else {
  form.value = {};
  form.value.inventoryUser = userInfo.name;
  // getCurrentTime();
}
const must = (obj) => {
  let mustColumns = [];
  mustColumns = [12, 13, 14];
  if (mustColumns.includes(obj.columnIndex)) {
    return "must";
  }
};
const handleType = (row) => {
  if (!form.value.inventoryMonth) {
    ElMessage({
      message: "请选择盘点月份",
      type: "warning",
    });
    form.value.inventoryStore = undefined;
    return;
  }
  if (!form.value.inventoryStore) {
    ElMessage({
      message: "请选择盘点仓库",
      type: "warning",
    });
    return;
  }
  mesInventoryDetailList.value = [];
  let machineId = undefined;
  if (form.value.inventoryStore != "0") {
    machineId = form.value.inventoryStore;
  }
  form.value.machineNo = undefined;
  mesInventoryDetailList.value = [];
  loading.value = true;
  detailsInventory({
    machineId,
    // type: form.value.inventoryStore,
    monthDate: form.value.inventoryMonth,
    pageNum: 1,
    pageSize: 100,
  }).then((response) => {
    loading.value = false;
    mesInventoryDetailList.value = response.rows.map((item) => {
      return {
        ...item,
        machineNumber: item.quantity,
      };
    });
    // response.rows.forEach((item) => {
    //   mesInventoryDetailList.value.push({
    //     ...item.mesPaper,
    //     // monthEnter: item.monthEnter,
    //     // monthLeave: item.monthLeave,
    //     paperid: item.paperid,
    //   });
    //   // mesInventoryDetailList.value.forEach((item) => {
    //   //   item.storeNumber = item.monthEnter - item.monthLeave;
    //   // });
    // });
  });
};

// 获取印刷机台
const getWorkDataList = () => {
  getDataList({ pageNum: 1, pageSize: 50, type: 2 }).then((res) => {
    console.log(res.rows);
    res.rows.forEach((item) => {
      item.label = item.machineName + "/" + item.workshopName;
      item.id = item.pid;
    });
    inventory_store.value = [{ label: "仓库", id: "0" }, ...res.rows];
  });
};
getWorkDataList();
const changeSearchWorkBenchData = (row) => {
  detailsInventory({
    // type: form.value.inventoryStore,
    monthDate: form.value.inventoryMonth,
    pageNum: 1,
    pageSize: 100,
  }).then((response) => {
    response.rows.forEach((item) => {
      mesInventoryDetailList.value.push({
        ...item.mesPaper,
        dayEnter: item.dayEnter,
        dayLeave: item.dayLeave,
        paperid: item.paperid,
      });
      // mesInventoryDetailList.value.forEach((item) => {
      //   item.storeNumber = item.monthEnter - item.monthLeave;
      // });
    });
  });
  searchVisible.value = false;
};
function getCurrentTime() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
  return (form.value.inventoryDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`);
}

const handleDel = (row) => {
  const index = mesInventoryDetailList.value.indexOf(row);
  if (index !== -1) {
    mesInventoryDetailList.value.splice(index, 1);
  }
};

// 盈亏计算
const changeInventoryNumber = (row) => {
  if(row.inventoryNumber!=""){
    row.profitLoss = toNumber(
    Number(row.inventoryNumber || 0) - Number(row.quantity || 0),
    4
  );
  }else{
    row.profitLoss=null;
  }
  
  console.log(row.profitLoss);
};
//保存
const handleSubmit = () => {
  cancellationRef.value.validate((valid) => {
    if (valid) {
      btnLoading.value = true;
      const formData = form.value;
      formData.mesInventoryDetailList = mesInventoryDetailList.value;
      if (formData.id) {
        updateInventory(formData)
          .then((response) => {
            if (response.code === 200) {
              ElMessage({
                message: "编辑成功",
                type: "success",
              });
              goBack();
            }
          })
          .catch((err) => {
            btnLoading.value = false;
          });
      } else {
        formData.status = 1;
        addInventory(formData)
          .then((response) => {
            if (response.code === 200) {
              ElMessage({
                message: "新增成功",
                type: "success",
              });
              goBack();
            }
          })
          .catch((err) => {
            btnLoading.value = false;
          });
      }
    }
  });
};

//  返回
const goBack = () => {
  tagsViewStore.delView(route);
  router.go(-1);
};
</script>

<style lang="scss" scoped>
:deep(.el-table th.must div:before) {
  content: "*";
  color: #ff1818;
}
</style>
